package com.cskaoyan.user.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cskaoyan.mall.commons.constant.SysRetCodeConstants;
import com.cskaoyan.mall.commons.result.ResponseData;
import com.cskaoyan.mall.commons.result.ResponseUtil;
import com.cskaoyan.user.constants.UserRetCode;
import com.cskaoyan.user.dto.UserLoginCheckResponse;
import com.cskaoyan.user.dto.UserLoginRequest;
import com.cskaoyan.user.dto.UserLoginResponse;
import com.cskaoyan.user.service.UserLoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author sosog
 * @version 1.0.0
 * @description TODO
 * @date 2022/6/17 21:26
 */
@RestController
@RequestMapping("/user")
public class UserLoginController {

    @Autowired
    UserLoginService userLoginService;

    @PostMapping("/login")
    public ResponseData login(@RequestBody UserLoginRequest request, HttpServletRequest servletRequest, HttpServletResponse servletResponse) {
        UserLoginResponse response = userLoginService.login(request, servletRequest, servletResponse);
        if (response.getCode().equals(UserRetCode.SUCCESS.getCode())) {
            return new ResponseUtil<>().setData(response);
        }
        return new ResponseUtil<>().setErrorMsg(response.getMsg());
    }

    @GetMapping("/login")
    public ResponseData checkLogin(HttpServletRequest request) {
        UserLoginCheckResponse response = new UserLoginCheckResponse();
        try {
            String userInfo = (String) request.getHeader("user_info");
            JSONObject object = JSON.parseObject(userInfo);
            Long uid = Long.parseLong(object.get("uid").toString());
            response.setUsername(object.get("username").toString());
            response.setUid(uid);
            response.setCode(UserRetCode.SUCCESS.getCode());
            response.setMsg(UserRetCode.SUCCESS.getMessage());
        } catch (Exception e) {
            response.setCode(SysRetCodeConstants.GET_TOKEN_FAILED.getCode());
            response.setMsg(SysRetCodeConstants.GET_TOKEN_FAILED.getMessage());
        }

        if (response.getCode().equals(UserRetCode.SUCCESS.getCode())) {
            return new ResponseUtil<>().setData(response);
        }
        return new ResponseUtil<>().setErrorMsg(response.getMsg());
    }
}
